/**
 * This file is a part of VideoCut package.
 * ---------------------------------------------------------------------- 
 * Copyright (C) 2007-2008 troorl
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * ---------------------------------------------------------------------- 
 *
 * @author troorl <troorl@gmail.com>
 */

#include "TMainWindow.h"

TMainWindow::TMainWindow(QWidget *parent) : QMainWindow(parent)
{
	isOpen = false;	
	mainTitle = APPLICATION_NAME "-" + QString(VERSION);
	if(STATUS != "release")
	{
		mainTitle += "-" + QString(STATUS);
	}
	
    settings = new TUserSettings();
	this->readSettings();
	
	GUI();
	this->menuInit();
	
	frames = new QList<frameStruct*>;

	connect(listPanel1, SIGNAL(changeItem(int)), this, SLOT(S_showCurrImage(int)));
	
	//showing main window
	this->show();
	this->setGeometry(settings->getGeometry());
	
	if(QFile::exists(qApp->argv()[1]))
	{
		this->path = qApp->argv()[1];
		this->openMain();
	}
}

TMainWindow::~TMainWindow()
{
	settings->setGeometry(this->geometry());
	settings->setShowPanel(!dock->isHidden());
	
	if(path != "")
		settings->setPath(this->fileInfo.path());
	
	settings->writeSettings();
	qApp->processEvents();
}

void TMainWindow::GUI()
{
	QPalette palette;
	QColor windowColor = this->palette().color(QPalette::Window);
	palette.setColor(QPalette::Dark, windowColor);
	palette.setColor(QPalette::Light, windowColor);
	palette.setColor(QPalette::Shadow, windowColor);
	palette.setColor(QPalette::Midlight, windowColor);
	palette.setColor(QPalette::Mid, windowColor);
	
	menubar = new QMenuBar();
	//menubar->setGeometry(QRect(0, 0, 640, 28));
	menuFile = new QMenu(menubar);
	menuFrame = new QMenu(menubar);
	menuOptions = new QMenu(menubar);
		menuToolbar = new QMenu(menuOptions);
	menuHelp = new QMenu(menubar);
	menuFile->setTitle(QApplication::translate("MainDialog", "File", 0, QApplication::UnicodeUTF8));
	menuFrame->setTitle(QApplication::translate("MainDialog", "Frame", 0, QApplication::UnicodeUTF8));
	menuOptions->setTitle(QApplication::translate("MainDialog", "Options", 0, QApplication::UnicodeUTF8));
	menuToolbar->setTitle(QApplication::translate("MainDialog", "Toolbar", 0, QApplication::UnicodeUTF8));
	menuHelp->setTitle(QApplication::translate("MainDialog", "Help", 0, QApplication::UnicodeUTF8));
	menubar->addAction(menuFile->menuAction());
	menubar->addAction(menuFrame->menuAction());
	menubar->addAction(menuOptions->menuAction());
	menubar->addAction(menuHelp->menuAction());
	this->setMenuBar(menubar);
	
	statusbar = new QStatusBar();
	this->setStatusBar(statusbar);
	
	this->setWindowTitle(mainTitle);
	QWidget *mainWidget = new QWidget();
	
	this->setWindowIcon(QIcon(":/img/logo.svg"));
	
	tabWidget = new QTabWidget(mainWidget);
	tabWidget->setMinimumHeight(350);
	tabWidget->setMinimumWidth(550);
	tabWidget->setTabPosition(QTabWidget::West);

	tab1 = new QWidget();
	tab1->setObjectName(QString::fromUtf8("tab1"));
	tab2 = new QWidget();
	tab2->setObjectName(QString::fromUtf8("tab2"));
	tabWidget->addTab(tab1, tr("Current frame"));
	tabWidget->addTab(tab2, tr("Preview"));
	tabWidget->setCurrentIndex(1);
	
	viewFrame1 = new TViewFrame(tab1);
	QHBoxLayout *labelImageLayout = new QHBoxLayout;
	labelImageLayout->setMargin(0);
	labelImageLayout->addWidget(viewFrame1);
	QVBoxLayout *tab1Layout = new QVBoxLayout;
	tab1Layout->setMargin(0);
	tab1Layout->addLayout(labelImageLayout);
	tab1->setLayout(tab1Layout);
	
	previewPanel1 = new TPreviewPanel(tab2);
	previewPanel1->setPalette(palette);
	QHBoxLayout *previewLayout = new QHBoxLayout;
	previewLayout->setMargin(0);
	previewLayout->addWidget(previewPanel1);
	
	
	styleBox = new QComboBox();
	styleBox->addItem("Shadowed");
	styleBox->addItem("Simple");
	styleBox->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));
	QLabel *styleLabel = new QLabel();
	styleLabel->setText(tr("Style"));
	QHBoxLayout *styleLayout = new QHBoxLayout;
	styleLayout->addWidget(styleLabel);
	styleLayout->addWidget(styleBox);
	connect(styleBox, SIGNAL(activated(int)), this, SLOT(S_ChangeStyle(int)));
	
	timePosBox = new QComboBox();
	timePosBox->addItem("Left & Top");
	timePosBox->addItem("Right & Top");
	timePosBox->addItem("Left & Bottom");
	timePosBox->addItem("Right & Bottom");
	timePosBox->addItem("None"); 
	timePosBox->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));
	QLabel *timePosLabel = new QLabel();
	timePosLabel->setText(tr("Timestamps"));
	QHBoxLayout *timePosLayout = new QHBoxLayout;
	timePosLayout->addWidget(timePosLabel);
	timePosLayout->addWidget(timePosBox);
	connect(timePosBox, SIGNAL(activated(int)), this, SLOT(S_ChangeTimePos(int)));
	
	sizeBox = new QSpinBox();
	sizeBox->setMinimum(10);
	sizeBox->setMaximum(100);
	sizeBox->setValue(0);
	QLabel *sizeLabel = new QLabel();
	sizeLabel->setText(tr("Size (%)"));
	QHBoxLayout *sizeLayout = new QHBoxLayout;
	sizeLayout->addWidget(sizeLabel);
	sizeLayout->addWidget(sizeBox);
	connect(sizeBox, SIGNAL(valueChanged(int)), this, SLOT(S_ChangeSize(int)));
	
	offsetBox = new QSpinBox();
	offsetBox->setMinimum(0);
	offsetBox->setValue(0);
	QLabel *offsetLabel = new QLabel();
	offsetLabel->setText(tr("Offset"));
	QHBoxLayout *offsetLayout = new QHBoxLayout;
	offsetLayout->addWidget(offsetLabel);
	offsetLayout->addWidget(offsetBox);
	connect(offsetBox, SIGNAL(valueChanged(int)), this, SLOT(S_ChangeOffset(int)));
	
	spaceBox = new QSpinBox();
	spaceBox->setMinimum(0);
	spaceBox->setValue(0);
	QLabel *spaceLabel = new QLabel();
	spaceLabel->setText(tr("Indentation"));
	QHBoxLayout *spaceLayout = new QHBoxLayout;
	spaceLayout->addWidget(spaceLabel);
	spaceLayout->addWidget(spaceBox);
	connect(spaceBox, SIGNAL(valueChanged(int)), this, SLOT(S_ChangeSpace(int)));
	
	colorBox = new TColorChoser();
	colorBox->setText(tr("Background"));
	colorBox->setColor(settings->getColorBackground());

	connect(colorBox, SIGNAL(colorChanged(QColor &)), this, SLOT(S_ChangeColor(QColor &)));
	
	//player = new TVideo();
	//connect(player, SIGNAL(ready()), this, SLOT(S_EnablePlayer()));
	
	QVBoxLayout *verDockLayout = new QVBoxLayout;
	verDockLayout->setAlignment(Qt::AlignTop);
	verDockLayout->addLayout(styleLayout);
	verDockLayout->addLayout(timePosLayout);
	verDockLayout->addLayout(sizeLayout);
	verDockLayout->addLayout(offsetLayout);
	verDockLayout->addLayout(spaceLayout);
	verDockLayout->addLayout(colorBox->getLayout());
	verDockLayout->addStretch(1);
	
	dock = new QDockWidget();
	dock->setWindowTitle(tr("Options panel"));
	dock->toggleViewAction()->setIcon(QIcon(":/img/viewpanel.png"));
	dock->toggleViewAction()->setShortcut(tr("Ctrl+."));
	
	//------- from settings
	if(!settings->getShowPanel())
	{
		dock->hide();
	}
	//--------------------
	
	dock->setAllowedAreas(Qt::RightDockWidgetArea);
	this->addDockWidget(Qt::RightDockWidgetArea, dock);
	toolBox = new QWidget(dock);
	toolBox->setEnabled(false);
	toolBox->setLayout(verDockLayout);
	
	dock->setWidget(toolBox);
	
	
	QVBoxLayout *tab2Layout = new QVBoxLayout;
	tab2Layout->setMargin(0);
	tab2Layout->setSpacing(0);
	tab2Layout->addLayout(previewLayout);
	tab2->setLayout(tab2Layout);
	
	listPanel1 = new TListPanel(mainWidget);
	int list_panel_height = listPanel1->horizontalScrollBar()->height() + 60;
	listPanel1->setMinimumHeight(list_panel_height);
	listPanel1->setMaximumHeight(list_panel_height);
	
	
	// Layouts
	QHBoxLayout *tabLayout = new QHBoxLayout;
	tabLayout->addWidget(tabWidget);
	
	QHBoxLayout *listLayout = new QHBoxLayout;
	listLayout->addWidget(listPanel1);
	
	QVBoxLayout *vertLayout = new QVBoxLayout;
	vertLayout->setMargin(0);
	vertLayout->setSpacing(0);
	vertLayout->addLayout(tabLayout);
	vertLayout->addLayout(listLayout);
	
	mainWidget->setLayout(vertLayout);
	
	QHBoxLayout *mainLayout = new QHBoxLayout;
	
	mainLayout->addWidget(mainWidget);
	this->setCentralWidget(mainWidget);
}

void TMainWindow::menuInit()
{
	openAct = new QAction(tr("&Open..."), this);
	openAct->setShortcut(tr("Ctrl+O"));
	openAct->setIcon(QIcon(":/img/fileopen.png"));
	openAct->setStatusTip(tr("Open video file"));
	
	openManyAct = new QAction(tr("&Open few files..."), this);
	openManyAct->setIcon(QIcon(":/img/filesopen.png"));
	openManyAct->setStatusTip(tr("Open video files"));
	
	closeAct = new QAction(tr("&Close"), this);
	closeAct->setShortcut(tr("Ctrl+Q"));
	closeAct->setIcon(QIcon(":/img/exit.png"));
	closeAct->setStatusTip(tr("Close program"));
	
	saveSceneAct = new QAction(tr("&Export..."), this);
	saveSceneAct->setShortcut(tr("Ctrl+E"));
	saveSceneAct->setIcon(QIcon(":/img/export.png"));
	saveSceneAct->setStatusTip(tr("Export composition to the graphics file"));
	saveSceneAct->setEnabled(false);
	previewPanel1->addAction(saveSceneAct);
	
	saveMultiAct = new QAction(tr("&Save like images..."), this);
	saveMultiAct->setShortcut(tr("Ctrl+M"));
	saveMultiAct->setIcon(QIcon(":/img/save_multi.png"));
	saveMultiAct->setStatusTip(tr("Save frames like many images"));
	saveMultiAct->setEnabled(false);
	
	printAct = new QAction(tr("&Print..."), this);
	printAct->setIcon(QIcon(":/img/print.png"));
	printAct->setStatusTip(tr("Print scene"));
	printAct->setEnabled(false);
	
	delFrameAct = new QAction(tr("Delete frame"), this);
	delFrameAct->setShortcut(tr("Ctrl+D"));
	delFrameAct->setIcon(QIcon(":/img/delete_frame.png"));
	delFrameAct->setStatusTip(tr("Delete current frame"));
	delFrameAct->setEnabled(false);
	
	saveFrameAct = new QAction(tr("Save frame"), this);
	saveFrameAct->setShortcut(tr("Ctrl+S"));
	saveFrameAct->setIcon(QIcon(":/img/save_frame.png"));
	saveFrameAct->setStatusTip(tr("Save current frame"));
	saveFrameAct->setEnabled(false);
	listPanel1->setActions(*delFrameAct, *saveFrameAct);
	
	optionsAct = new QAction(tr("Options"), this);
	optionsAct->setShortcut(tr("Ctrl+P"));
	optionsAct->setIcon(QIcon(":/img/options.png"));
	optionsAct->setStatusTip(tr("Go to options"));
	
	sizeGroup = new QActionGroup(this);
	sizeGroup->setExclusive(true);
		size16 = new QAction(tr("16"), this);
		size16->setCheckable(true);
		
		size24 = new QAction(tr("24"), this);
		size24->setCheckable(true);
		
		size32 = new QAction(tr("32"), this);
		size32->setCheckable(true);
		
		size48 = new QAction(tr("48"), this);
		size48->setCheckable(true);
	sizeGroup->addAction(size16);
	sizeGroup->addAction(size24);
	sizeGroup->addAction(size32);
	sizeGroup->addAction(size48);
	
	switch(settings->getToolbarSize())
	{
		case(16):
		{
			size16->setChecked(true);
			break;
		}
		case(24):
		{
			size24->setChecked(true);
			break;
		}
		case(32):
		{
			size32->setChecked(true);
			break;
		}
		case(48):
		{
			size48->setChecked(true);
			break;
		}
	}
	
	aboutAct = new QAction(tr("About..."), this);
	aboutAct->setShortcut(tr("F1"));
	aboutAct->setIcon(QIcon(":/img/about.png"));
	aboutAct->setStatusTip(tr("About program"));
	
	aboutQtAct = new QAction(tr("About Qt..."), this);
	aboutQtAct->setIcon(QIcon(":/img/qt_logo.png"));
	aboutQtAct->setStatusTip(tr("About Qt framework"));
	
	menuFile->addAction(openAct);
	menuFile->addAction(openManyAct);
	menuFile->addAction(saveSceneAct);
	menuFile->addAction(saveMultiAct);
	menuFile->addAction(printAct);
	menuFile->addSeparator();
	menuFile->addAction(closeAct);
	
	menuFrame->addAction(delFrameAct);
	menuFrame->addAction(saveFrameAct);
	
	menuToolbar->addAction(size16);
	menuToolbar->addAction(size24);
	menuToolbar->addAction(size32);
	menuToolbar->addAction(size48);
	
	menuOptions->addAction(optionsAct);
	menuOptions->addAction(dock->toggleViewAction());
	menuOptions->addMenu(menuToolbar);
	
	menuHelp->addAction(aboutAct);
	menuHelp->addAction(aboutQtAct);
	
	connect(openAct, SIGNAL(triggered()), this, SLOT(S_OpenFile()));
	connect(openManyAct, SIGNAL(triggered()), this, SLOT(S_OpenFiles()));
	connect(saveSceneAct, SIGNAL(triggered()), this, SLOT(S_SaveScene()));
	connect(delFrameAct, SIGNAL(triggered()), this, SLOT(S_DelFrame()));
	connect(saveFrameAct, SIGNAL(triggered()), this, SLOT(S_SaveCurrImage()));
	connect(saveMultiAct, SIGNAL(triggered()), this, SLOT(S_SaveAllImages()));
	connect(printAct, SIGNAL(triggered()), this, SLOT(S_PrintScene()));
	connect(closeAct, SIGNAL(triggered()), this, SLOT(S_Exit()));
	connect(optionsAct, SIGNAL(triggered()), this, SLOT(S_Options()));
	connect(aboutAct, SIGNAL(triggered()), this, SLOT(S_About()));
	connect(aboutQtAct, SIGNAL(triggered()), this, SLOT(S_AboutQt()));
	
	connect(size16, SIGNAL(toggled(bool)), this, SLOT(S_ChangeSizeToolbar(bool)));
	connect(size24, SIGNAL(toggled(bool)), this, SLOT(S_ChangeSizeToolbar(bool)));
	connect(size32, SIGNAL(toggled(bool)), this, SLOT(S_ChangeSizeToolbar(bool)));
	connect(size48, SIGNAL(toggled(bool)), this, SLOT(S_ChangeSizeToolbar(bool)));
	
	// creating toolbar
	toolbar = new QToolBar(tr("Main toolbar"), this);
	int toolbarSize = settings->getToolbarSize();
	toolbar->setIconSize(QSize(toolbarSize, toolbarSize));
	toolbar->addAction(openAct);
	toolbar->addAction(openManyAct);
	toolbar->addAction(saveSceneAct);
	toolbar->addAction(saveMultiAct);
	toolbar->addAction(printAct);
	toolbar->addSeparator();
	toolbar->addAction(delFrameAct);
	toolbar->addAction(saveFrameAct);
	toolbar->addSeparator();
	toolbar->addAction(optionsAct);
	toolbar->addAction(dock->toggleViewAction());
	toolbar->addSeparator();
	toolbar->addAction(aboutAct);
	this->addToolBar(toolbar);
}

void TMainWindow:: deleteAllItems()
{
	previewPanel1->removeAll();
	listPanel1->removeAll();
	
	// deleting buffers
	for(int i = 0; i < frames->count(); i++)
	{
		delete []frames->at(i)->img.bits();
	}
	
	//qDeleteAll(*frames);
	frames->clear();
	delete frames;
	frames = new QList<frameStruct*>;
	
	videocodec = "";
	audiocodec = "";
	
	/*if(player->isOpen())
	{
		player->closeBackend();
		player->check(false);
	}*/
}

void TMainWindow::S_OpenFile()
{
	this->path = QFileDialog::getOpenFileName(this, tr("Open File"),
											  settings->getPath(),
			 tr("Video (*.avi *.mpg *.mpeg *.ogg *.wmv *.mov *.mkv);; All (*.*)"));

	if(path != "")
	{
		if(!QFile::exists(this->path))
		{
			QMessageBox::information(0, APPLICATION_NAME, tr("invalid path!"));
			return;
		}
		else
			this->openMain();
	}
}

void TMainWindow::S_OpenFiles() // for few files
{
	this->paths = QFileDialog::getOpenFileNames(this, tr("Open File"),
											  settings->getPath(),
													  tr("Video (*.avi *.mpg *.mpeg *.ogg *.wmv *.mov *.mkv);; All (*.*)"));

	if(!this->paths.empty())
	{
		this->openManyMain();
	}
}

void TMainWindow::openMain()
{
	this->setWindowTitle(mainTitle + " - " + this->path);
	
	this->deleteAllItems();
	fileInfo = QFileInfo(this->path);
	settings->setPath(fileInfo.path());
	settings->writeSettings();
	
	//------------TEST!!!---------------------
	/*backend1 = new TFfmpeg();
	backend1->init(path.toLocal8Bit());
	qWarning() << "LENGTH (ffmpeg): " <<backend1->getLength();
	backend1->close();
	delete backend1;*/
	//----------------------------------------
	
	backend = new TXine();
	int error = backend->init(path.toLocal8Bit());
	
	if(error == CANT_FIND_VIDEO_CODEC)
	{
		QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't open video driver!"));
		backend->close();
		delete backend;
		return;
	}
	
	if(error == CANT_OPEN_FILE)
	{
		QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't open video file!"));
		backend->close();
		delete backend;
		return;
	}
	
	videocodec = backend->videoCodec();
	audiocodec = backend->audioCodec();
	length = backend->getLength();
		
	this->perfectFile(false);
	
	backend->close();
	delete backend;
	
	this->makePreview(false);
	
	//player->init(path);
	
	toolBox->setEnabled(true);
	styleBox->setCurrentIndex(previewPanel1->getItemStyle());
	sizeBox->setValue((int)(previewPanel1->getScale() * 100));
	offsetBox->setValue(previewPanel1->getOffset());
	spaceBox->setValue(previewPanel1->getSpace());
	colorBox->setColor(settings->getColorBackground()); 
	
	QImage *tmpImage = new QImage();
	*tmpImage = frames->at(0)->getImage();
	viewFrame1->setImage(*tmpImage);
	viewFrame1->setWorkScene();
	
	isOpen = true;
	saveSceneAct->setEnabled(true);
	saveMultiAct->setEnabled(true);
	printAct->setEnabled(true);
	saveFrameAct->setEnabled(true);
	delFrameAct->setEnabled(true);
}

void TMainWindow::openManyMain()
{
	QProgressDialog *progress = new QProgressDialog(); 
	progress->setRange(0, paths.count());
	progress->setLabel(new QLabel(tr("Processing video files...")));
	progress->setCancelButton(NULL);
	progress->setWindowModality(Qt::WindowModal);
	//progress->show();
	
	//test
	prog = new TProgress;
	prog->setRangeTop(0, paths.count());
	prog->setLabel(tr("Processing video files..."));
	prog->show();
	qApp->processEvents();
	
	for(int i = 0; i < paths.count(); i++)
	{
		prog->setCurrentFile(paths.at(i));
		qApp->processEvents();
		
		prog->setValueTop(i);
		
		this->deleteAllItems();
		fileInfo = QFileInfo(this->paths.at(i));
		settings->setPath(fileInfo.path());
		settings->writeSettings();
		
		backend = new TXine();
		int error = backend->init(paths.at(i).toLocal8Bit());
		
		if(error == CANT_FIND_VIDEO_CODEC)
		{
			QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't open video driver!"));
			backend->close();
			delete backend;
			return;
		}
		
		if(error == CANT_OPEN_FILE)
		{
			QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't open video file!"));
			backend->close();
			delete backend;
			return;
		}
		
		videocodec = backend->videoCodec();
		audiocodec = backend->audioCodec();
		length = backend->getLength();
			
		this->perfectFile(true);
		
		backend->close();
		delete backend;
		
		this->makePreview(true);
		
		//default format
		QString df = "";
		switch(settings->getFormatImg())
		{
			case(0):
			{
				df = ".png";
				break;
			}
			case(1):
			{
				df = ".jpg";
				break;
			}
			case(2):
			{
				df = ".xpm";
				break;
			}
		}
		
		previewPanel1->saveToFile(paths.at(i) + df);
		//isOpen = true;
		
		qApp->processEvents();
	}
	
	delete progress;
	delete prog;
}

void TMainWindow::perfectFile(bool many)
{
	QTime *startTime = new QTime(0, 0, 0);
	QTime *finishTime = new QTime(0, 0, 0);
	int start = startTime->msecsTo(settings->getIndentTimeStart());
	int finish = finishTime->msecsTo(settings->getIndentTimeFinish());
	delete startTime;
	delete finishTime;
	
	if(start > (length - finish))
	{
		start = 0;
		finish = 0;
	}
	
	int step = settings->getCountFrames()!=1 ? (this->length - start - finish)/(settings->getCountFrames() - 1) : 0;
	int j = start;//step;
	
	QProgressDialog *progress = new QProgressDialog(); 
	if(!many) // for one file
	{
		progress->setRange(0, settings->getCountFrames());
		progress->setLabel(new QLabel(tr("Processing video file...")));
		progress->setCancelButton(NULL);
		progress->setWindowModality(Qt::WindowModal);
		progress->show();
	}
	else
	{
		prog->setRangeBottom(0, settings->getCountFrames());
	}
	
	for(int i = 0; i < settings->getCountFrames(); i++)
	{
		if(!many) // for one file
			progress->setValue(i);
		else
			prog->setValueBottom(i);
		
		int width, height;
		
		//QImage *image = new QImage(backend->getCurrentFrame(j, &width, &height), width, height, QImage::Format_RGB32);
		QImage image = backend->getCurrentFrame(j);//, &width, &height);
		QString temp_s = timeToString(j);
		
		frames->append(new frameStruct(image, temp_s));

		qApp->processEvents();
		j = j + step;
	}
	
	if(!many)
		delete progress;
}

void TMainWindow::makePreview(bool many)
{	
	previewPanel1->setOffsetValue(settings->getIndentBorder());
	previewPanel1->setScaleValue(settings->getScale() * .01);
	previewPanel1->setSpaceValue(settings->getIndentItems());
	previewPanel1->setQuality(settings->getQuality());
	previewPanel1->setCountHor(settings->getCountHor());
	previewPanel1->setfontMetaInfo(settings->getFontMetaInfo());
	previewPanel1->setColorInfoText(settings->getColorInfoText());
	previewPanel1->setColorInfoInfo(settings->getColorInfoInfo());
	previewPanel1->setBackgroundColorValue(settings->getColorBackground());
	
	QString *fileSize = new QString(QString::number(fileInfo.size() / 1024 / 1024) + "Mb");
	
	QString *infoText = new QString();
	QString *infoInfo = new QString();
	
	if(settings->getInfoName())
	{ 
		*infoText += "Title: \n";
		*infoInfo += this->fileInfo.fileName() + "\n";
	}
	if(settings->getInfoSize())
	{
		*infoText += "Size: \n";
		*infoInfo += *fileSize + "\n";
	}
	if(settings->getInfoDuration())
	{
		*infoText += "Duration: \n";
		*infoInfo += timeToString(length) + "\n";
	}
	if(settings->getInfoResolution())
	{
		*infoText += "Resolution: \n";
		*infoInfo += QString::number(frames->at(0)->img.width()) + "x" + QString::number(frames->at(0)->img.height()) + "\n";
	}
	if(settings->getInfoVideo())
	{
		*infoText += "Video: \n";
		if(videocodec == "")
			videocodec == "None";
		*infoInfo += videocodec + "\n";
	}
	if(settings->getInfoAudio())
	{
		*infoText += "Audio: \n";
		if(audiocodec == "")
			audiocodec = "None";
		*infoInfo += audiocodec + "\n";
	}
	
	previewPanel1->addText(*infoText, *infoInfo);
	delete fileSize;
	delete infoText;
	delete infoInfo;

	previewPanel1->setList(frames);
	previewPanel1->createItems();	
	previewPanel1->prepare(); 
	
	// show logo
	if(settings->getLogo())
		previewPanel1->addLogo();
	
	//previewPanel1->adjustItems();
	previewPanel1->setItemsStyle(settings->getStyle());
	
	if(!many)
	{
		previewPanel1->setSceneAfter();
		offsetBox->setValue(previewPanel1->getOffset());
		listPanel1->setList(frames);
		listPanel1->createItems();
		listPanel1->adjustItems();
	}
	
	previewPanel1->adjustItems();
}

void TMainWindow::S_DelFrame()
{
	if(frames->count() > 0)
	{
		QWidget::setCursor(Qt::BusyCursor);
		
		int index = listPanel1->getCurrentIndex();
		
		delete []frames->at(index)->img.bits();
		
		listPanel1->deleteItem(index);
		previewPanel1->deleteItem(index);
		
		frames->removeAt(index);
		
		QWidget::setCursor(Qt::ArrowCursor);
	}
}

void TMainWindow::S_SaveScene()
{
	if(isOpen)
	{
		QString fileName = QFileDialog::getSaveFileName(this, tr("Saving..."), \
				this->path + ".png", \
						tr("PNG image (*.png);;JPG image (*.jpg);;XPM image (*.xpm)"));
		if(fileName != "")
		{
			if(!previewPanel1->saveToFile(fileName))
			{
				QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't save this file"));
			}
		}
	}
}

void TMainWindow::S_PrintScene()
{
	QPrinter printer;
	QPrintDialog dialog(&printer, this);
	if (dialog.exec() == QDialog::Accepted)
	{
		previewPanel1->print(printer);
	}
}

void TMainWindow::S_showCurrImage(int curritem)
{
	QImage *tmpImage = new QImage();
	*tmpImage = frames->at(curritem)->getImage();
	viewFrame1->setImage(*tmpImage);
}

QString TMainWindow::timeToString(int currPos)
{
	QTime t(0, 0, 0);
	t = t.addMSecs(currPos);
	QString temp_s = t.toString("hh:mm:ss");
	return temp_s;
}

void TMainWindow::S_Options()
{
	optionsDialog = new TConfigDialog();
	optionsDialog->show();
	connect(optionsDialog, SIGNAL(applySettings()), this, SLOT(S_ApplyChanges()));
}

void TMainWindow::S_ApplyChanges()
{
    settings->sync();
    settings->readSettings();
	
	if(isOpen)
	{
	//applying for preview
	previewPanel1->setScale(settings->getScale() * .01);
	previewPanel1->setSpace(settings->getIndentItems());
	previewPanel1->setQuality(settings->getQuality());
	previewPanel1->setOffset(settings->getIndentBorder());
	previewPanel1->setItemsStyle(settings->getStyle());
	QColor *tmp_color = new QColor(settings->getColorBackground());
	previewPanel1->setBackgroundColor(*tmp_color);
	
	if(settings->getLogo())
	{
		previewPanel1->addLogo();
		previewPanel1->adjustItems();
	}
	else
	{
		previewPanel1->removeLogo();
	}
	
	//applying for toolbox
	styleBox->setCurrentIndex(previewPanel1->getItemStyle());
	sizeBox->setValue((int)(previewPanel1->getScale()*100));
	offsetBox->setValue(previewPanel1->getOffset());
	spaceBox->setValue(previewPanel1->getSpace());
	colorBox->setColor(settings->getColorBackground());
	}
}

void TMainWindow::readSettings()
{
    settings->sync();
    settings->readSettings();
}

void TMainWindow::S_SaveCurrImage()
{
	if(isOpen)
	{
		QString fileName = QFileDialog::getSaveFileName(this, tr("Save frame"), \
								"/media/sda6/shot.png", \
								tr("PNG image (*.png);;JPG image (*.jpg);;XPM image (*.xpm)"));
		if(fileName !="")
		{
			if(!frames->at(listPanel1->getCurrentIndex())->img.save(fileName))
			{
				QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't save this file"));
			}
		}
	}
}

void TMainWindow::S_SaveAllImages()
{
	QString dirName = QFileDialog::getExistingDirectory(this, tr("Choose directory"), \
			fileInfo.path(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
	if(dirName != "")
	{
		QProgressDialog *progress = new QProgressDialog(); 
		progress->setRange(0, frames->count());
		progress->setLabel(new QLabel(tr("Saving images...")));
		progress->setCancelButton(NULL);
		progress->setWindowModality(Qt::WindowModal);
		progress->show();
		
		for(int i = 0; i < frames->count(); i++)
		{
			qApp->processEvents();
			progress->setValue(i);
			if(!frames->at(i)->img.save(dirName + this->fileInfo.fileName() + QString::number(i) + ".png"))
			{
				QMessageBox::critical(0, APPLICATION_NAME, tr("Error! Can't save this file"));
				break;
			}
		}
		delete progress;
	}
}

void TMainWindow::S_ChangeSizeToolbar(bool checked)
{
	if(checked)
	{
		int size = 0;
		
		if(this->sender() == size16)
		{
			size = 16;
		}
		if(this->sender() == size24)
		{
			size = 24;
		}
		if(this->sender() == size32)
		{
			size = 32;
		}
		if(this->sender() == size48)
		{
			size = 48;
		}
		
		toolbar->setIconSize(QSize(size, size));
		this->settings->setToolbarSize(size);
		this->settings->writeSettings();
	}
}

void TMainWindow::S_AboutQt()
{
	QApplication::aboutQt();
}

void TMainWindow::S_About()
{
	aboutWindow = new TAboutWindow();
	aboutWindow->show();
}

void TMainWindow::S_ChangeStyle(int style)
{
	switch(style)
	{
		case(0):
		{
			previewPanel1->setItemsStyle(shadow);
			break;
		}
		case(1):
		{
			previewPanel1->setItemsStyle(seample);
			break;
		}
	}
}

void TMainWindow::S_ChangeTimePos(int pos)
{
	previewPanel1->setItemTextPos(pos);
}

void TMainWindow::S_ChangeSize(int size)
{
	previewPanel1->setScale(size * 0.01);
	previewPanel1->adjustItems();
}

void TMainWindow::S_ChangeOffset(int offset)
{
	previewPanel1->setOffset(offset);
	//previewPanel1->adjustItems();
}

void TMainWindow::S_ChangeSpace(int space)
{
	previewPanel1->setSpace(space);
	//previewPanel1->adjustItems();
}

void TMainWindow::S_ChangeColor(QColor &color)
{
	previewPanel1->setBackgroundColor(color);
}

void TMainWindow::S_Exit()
{
	qApp->quit();
}

/*void TMainWindow::S_EnablePlayer()
{
	if(!player->isOpen())
	{
		player->init(path);
	}
}*/
